﻿using CommonMvc.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NLog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace CommonMvc.Filters
{
    public class ModelFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            var httpContext = context.HttpContext;
            var stopwach = httpContext.Items["runtime"] as Stopwatch;
            stopwach.Stop();
            var time = stopwach.Elapsed;
            var log = LogManager.GetLogger("file");
            log.Trace("运行时间" + time);
            
            //throw new NotImplementedException();
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var stopwach = new Stopwatch();
            stopwach.Start();
            context.HttpContext.Items.Add("runtime", stopwach);
            if (!context.ModelState.IsValid)
            {
                BaseResult result = new BaseResult() { ResultCode = 1 };

                foreach (var item in context.ModelState.Values)
                {
                    foreach (var error in item.Errors)
                    {
                        result.Message += error.ErrorMessage + "|";
                    }
                }
                context.Result = new JsonResult(result);
            }
            
        }
    }
}
